<template>
  <div class="page">
    <BrandHeader>
      <template #title>光影漫荐</template>
    </BrandHeader>
    <div class="content">
        <div class="topbar">
          <button class="back-btn" @click="goBack" aria-label="返回上一页">返回</button>
          <h1 class="title">热门电影</h1>
          <div class="spacer"></div>
          <button class="link-btn" @click="goMovies" aria-label="前往全部电影">全部电影</button>
        </div>
      <div class="grid">
        <MovieCard
          v-for="m in hot35"
          :key="m.id"
          :movie="m"
          :cardWidth="200"
          :posterHeight="260"
          @select="goDetail"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import BrandHeader from '@/components/BrandHeader.vue'
import MovieCard from '@/components/MovieCard.vue'
import { fetchHotMovies } from '@/services/movie.js'
import { hotMoviesCache } from '@/services/cache.js'

const router = useRouter()
const movies = ref([])

const hot35 = computed(() => movies.value.slice(0, 35))

function mapMovie(m, idx) {
  return {
    id: m.movieId ?? m.id ?? idx,
    title: m.title ?? '未知标题',
    rating: Number(m.predicted_rating ?? m.rating_mean ?? (8 + Math.random()).toFixed(1)),
    poster: m.poster || m.poster_path || '',
    backdrop: m.backdrop || m.backdrop_path || m.banner || m.landscape || m.horizontal_image || '',
    overview: m.overview || '',
    year: m.year || '',
    genres: m.genres || ''
  }
}

async function load() {
  // 1) 先用缓存（TTL 内）立即渲染；不清空缓存，便于返回时仍保持
  const cached = hotMoviesCache.get()
  if (Array.isArray(cached) && cached.length) {
    movies.value = cached.map(mapMovie)
  }
  // 2) 若不足 35 条或没有缓存，再请求补齐（避免二次请求影响首屏）
  if (!Array.isArray(movies.value) || movies.value.length < 35) {
    try {
      const need = 35
      const res = await fetchHotMovies(need)
      const list = Array.isArray(res.data) ? res.data.map(mapMovie) : []
      // 若缓存已有一部分，用 movie.id 去重合并
      const existingIds = new Set((movies.value || []).map(m => m.id))
      const merged = [...(movies.value || [])]
      for (const item of list) {
        if (!existingIds.has(item.id)) merged.push(item)
        if (merged.length >= need) break
      }
      movies.value = merged.slice(0, need)
      // 更新缓存，确保后续在 TTL 内稳定
      hotMoviesCache.set(movies.value)
    } catch (e) {
      // 保持已有缓存显示
    }
  }
}

function goDetail(id) {
  if (!id) return
  router.push({ name: 'movie', params: { id } })
}

function goBack() {
  if (window.history.length > 1) router.back()
  else router.push('/recommend')
}

function goMovies() {
  router.push({ name: 'movies' })
}

onMounted(load)
</script>

<style scoped>
.page { min-height: 100vh; background: #0f0f0f; color: #fff; }
.content { padding: 10px 16px 20px; }
.topbar { display:flex; align-items: center; gap: 12px; margin: 4px 0 10px; }
.back-btn {
  background: #fff;
  color: #000;
  border: 1px solid #e5e5e5;
  border-radius: 10px;
  padding: 8px 14px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: background .15s ease, transform .1s ease;
}
.back-btn:hover { background: #f2f2f2; transform: translateY(-1px); }
.back-btn:focus-visible { outline: 2px solid #000; outline-offset: 2px; }
.title { margin: 0; font-size: 22px; font-weight: 700; }
.spacer { flex: 1; }
.link-btn {
  background: #ff4e4e;
  color: #fff;
  border: 1px solid #ff4e4e;
  border-radius: 10px;
  padding: 8px 14px;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  transition: background .15s ease, border-color .15s ease, transform .1s ease;
}
.link-btn:hover { background: #ff3333; border-color: #ff3333; transform: translateY(-1px); }

/* 7列 x 5行，卡片宽度与 MovieCard 保持一致（180px） */
.grid {
  display: grid;
  grid-template-columns: repeat(7, 200px);
  gap: 28px;
  justify-content: start;
}

@media (max-width: 1400px) {
  .grid { grid-template-columns: repeat(6, 200px); }
}
@media (max-width: 1200px) {
  .grid { grid-template-columns: repeat(5, 200px); }
}
@media (max-width: 1000px) {
  .grid { grid-template-columns: repeat(4, 200px); }
}
@media (max-width: 820px) {
  .grid { grid-template-columns: repeat(3, 200px); }
}
@media (max-width: 620px) {
  .grid { grid-template-columns: repeat(2, 200px); }
}
</style>
